package com.sky.task;


import com.sky.entity.Orders;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersService ordersService;

    /**
     *  处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟触发一次
//    @Scheduled(cron = "0/5 * * * * ?") // test
    public void executeTask(){
        ;log.info("开始处理超时订单");
//        log.info("定时任务开始执行:{}", new Date());
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);

         List<Orders> ordersList = ordersService.GetByStatusAndOrderTime(
                Orders.PENDING_PAYMENT,
                dateTime
        );
         if (ordersList!=null&&ordersList.size()!=0){
             ordersList.stream().forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                 ordersService.updateById(order);
             });
         }
    }

    /**
     * 处理一直派送中的订单
     */
    @Scheduled(cron ="0 0 1 * * ?") // 分天凌晨1点触发
//    @Scheduled(cron = "0/5 * * * * ?") // test
    public void processDeliverOrder(){
        log.info("开始处理一直派送中的订单");
         LocalDateTime dateTime = LocalDateTime.now().plusHours(-1);
         List<Orders> ordersList = ordersService.GetByStatusAndOrderTime(
                Orders.DELIVERY_IN_PROGRESS,
                dateTime
        );
        if (ordersList!=null&&ordersList.size()!=0){
            ordersList.stream().forEach(order->{
                order.setStatus(Orders.COMPLETED);
                ordersService.updateById(order);
            });
        }
    }
}
